package cc.c3p0.admin.controller;

import cc.c3p0.admin.common.annotation.CurrentUser;
import cc.c3p0.admin.common.dto.Json;
import cc.c3p0.admin.common.model.AccessToken;
import cc.c3p0.admin.module.user.service.UserServiceI;
import cc.c3p0.admin.module.user.vo.UserVO;
import cc.c3p0.admin.mybatis.model.AdminGroup;
import cc.c3p0.admin.mybatis.model.AdminUser;
import cc.c3p0.admin.utils.JwtHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * Token controller
 * Created by binchao on 2017/5/5.
 */
@RestController
@RequestMapping("/tokens")
public class TokenController {

    private static final Logger LOG = LoggerFactory.getLogger(TokenController.class);

    @Value("${system.jwt.ttlmillis}")
    private Long jwtTTLMillis;

    @Value("${system.jwt.secretkey}")
    private String jwtSecretKey;

    @Resource
    private UserServiceI userService;

    @PostMapping("/login")
    public Json login(@RequestBody UserVO user) {
        Json json = new Json();
        if (null != user && !StringUtils.isEmpty(user.getUsername()) &&
                !StringUtils.isEmpty(user.getPassword())) {
            try {
                AdminUser u = userService.login(user);
                AccessToken accessToken = new AccessToken();
                String token = JwtHelper.createJWT(u.getId(), u.getUsername(), u.getGids(), jwtTTLMillis, jwtSecretKey);
                accessToken.setAccessToken(token);
                accessToken.setTokenType("Bearer");
                accessToken.setExpiresIn(jwtTTLMillis);
                Map<String, Object> result = new HashMap<String, Object>();
                result.put("tokenObj", accessToken);
                result.put("user", u);
                json.setObj(result);
                json.setSuccess(true);
                json.setMsg("登录成功！");
            } catch (Exception e) {
                LOG.error("登录失败：" + e.getMessage(), e);
                json.setMsg("登录失败：" + e.getMessage());
            }
        } else {
            json.setMsg("用户名及密码不能为空！");
        }
        return json;
    }

    /**
     * 刷新token
     * @param user 当前登录用户
     * @return
     */
    @RequestMapping("/refresh")
    public Json refresh(@CurrentUser AdminUser user) {
        Json json = new Json("令牌刷新成功!");
        if (user != null) {
            String token = JwtHelper.createJWT(user.getId(), user.getUsername(), user.getGids(), jwtTTLMillis, jwtSecretKey);
            AccessToken accessToken = new AccessToken();
            accessToken.setAccessToken(token);
            accessToken.setExpiresIn(jwtTTLMillis);
            json.setObj(accessToken);
            json.setSuccess(true);
        } else {
            json.setMsg("令牌刷新失败！");
        }
        return json;
    }

//    @RequestMapping("/logout")
//    public Json logout(@CurrentUser AdminUser user) {
//        Json json = new Json();
//        try {
////            tokenManager.deleteToken(user.getId());
//            json.setSuccess(true);
//            json.setMsg("成功退出！");
//        } catch (Exception e) {
//            LOG.error("注销失败：{}", e.getMessage());
//        }
//        return json;
//    }
}
